# encoding=utf8
# !/usr/bin/python
import datetime
import time
import paho.mqtt.client as mqtt
import ssl
ssl.match_hostname = lambda cert, hostname: True
from RaspiCode.mysqlUtils import PdbcUtil
from RaspiCode.Filter import filter, filterUtils
class DataProcessor():
    def __init__(self):
        # self.mqttClient = MyMqttClient()
        # self.pdbcUtils = PdbcUtil()
        # self.queue = Queue()
        # self.mqttClient.queue = self.queue
        self.rhFilterQueue = []
        self.co2FilterQueue = []
        self.tvocFilterQueue = []
        self.lightFilterQueue=[]
        self.lastSentTime = time.time()

    # def getCommand(self, cmd: str):

    def sendCommand(self, cmd: str):

        f = self.mqttClient.publish('control', cmd, 1)
        if (self.mqttClient._inflight_messages > 0):  # 我也不知道这个库为什么会犯这个毛病，总之似乎不太对劲……
            self.mqttClient._inflight_messages -= 1

        self.lastSentTime = time.time()

    # def controlProcess(self):
    #     while (1):
    #         time.sleep(0.1)
    #         cmd = requestFromServer('117.73.9.242')
    #
    #         if (cmd == None):  # 没有任何任务的话就继续
    #             continue
    #         else:
    #
    #             angle = cmd['motion'][0]
    #             self.sendCommand("<%s>" % angle)


    def continousFiltering(self, row):

        l = row.strip().split(',')
        print(l)
        temp = float(l[0])
        rh = float(l[1])
        light = float(l[2])

        rh, self.rhFilterQueue = filterUtils(rh, self.rhFilterQueue, r=2 * 10 ** -3, q=8 * 10 ** -5)
        light, self.lightFilterQueue = filterUtils(light, self.lightFilterQueue, r=10 ** -4.2, q=10 ** -5.2)
        print(self.rhFilterQueue)
        print(self.lightFilterQueue)
        return temp, rh, light




class MyMqttClient(mqtt.Client):
    def __init__(self, clientId="", cleanSession=None, userData=None,
                 protocol=4, transport="tcp"):
        super(MyMqttClient, self).__init__(client_id=clientId, clean_session=cleanSession, userdata=userData
                                           , protocol=4, transport="tcp")
        self.queue=None
        self.strBroker = "117.51.142.180"  # 服务器地址
        self.port = 2883
        self.topic = clientId
        print('开始连接远程服务器……')

        self.tls_set(ca_certs='/home/hzy/Documents/WeChat Files/hzy15610046011/FileStorage/File/2020-03/ca.crt')
        self.connect(self.strBroker, self.port, 60)
        print("设备启动完成")
        self.subscribe('#', 0)
        # self.subscribe('temp',0)
        # self.subscribe('RH',0)
        # self.subscribe('lig',0)
        self.mysqlUtil=PdbcUtil()
        self.dataProcessor=DataProcessor()




    def on_connect(self, aa, mqttC, obj, rc):
        # super().on_connect()
        print("OnConnetc, rc: " + str(rc))

    def on_publish(self, mqttC, obj, mid):
        # super().on_publish()
        print("OnPublish, mid: " + str(mid))

    def on_subscribe(self, mqttC, obj, mid, granted_qos):
        # super().on_subscribe()
        print("Subscribed: " + str(mid) + " " + str(granted_qos))

    def on_log(self, mqttC, obj, level, string):
        print("Log:" + string)

    def on_message(self, mqttc, obj, msg):
        # super().on_message()
        curtime = datetime.datetime.now()
        strCurtime = curtime.strftime("%Y-%m-%d %H:%M:%S")
        print(strCurtime + ": " + msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
        print(msg.payload,msg.payload.decode('utf-8'))
        s=msg.payload.decode('utf-8')

        if(s.find(':'))!=-1:

            try:
                l1=s.split(':')
                sensorId=l1[0].strip()
                l2=l1[1].split(',')
                f = open("log.csv", "a")
                f.write(l1[1]+'\n')
                f.close()
                RH=float(l2[1])
                temp=float(l2[0])
                light=float(l2[2])
                temp,RH,light=self.dataProcessor.continousFiltering(l1[1].strip())
                self.mysqlUtil.insertData2(sensorId=sensorId,RH=RH,temp=temp,light=light)
            except Exception as e:
                import  traceback
                traceback.print_exc()




        self.mysqlUtil.insertData(topic=msg.topic,message=msg.payload.decode('utf-8'),qos=msg.qos)


    def readSensor(self, strcmd=''):
        t = time.time()
        l = strcmd.split(",")
        temp = l[0]
        rh = l[1]
        co2 = l[2]
        tvoc = l[3]
        f = open("log.txt", "a")
        f.write(repr(int(t)) + ',' + temp + ',' + rh + ',' + co2 + ',' + tvoc + '\n')
        f.close()
        print("value:", strcmd)
        if(self.queue==None):
            return
        else:
            tmpl=[]
            tmpl.append(int(t))
            for i in l:
                tmpl.append(float(i))
            self.queue.put(tmpl)


if __name__ == '__main__':
    m = MyMqttClient('test')
    m.loop_forever()
